#!/usr/bin/env python
# -*- coding: utf-8 -*-

from pwpd.common import config
from pwpd.core import pwdlogging
from pwpd.core import pwdcore
import time
import os, sys

DEFAULT_CONFIG = os.path.join(os.getcwd(), 'etc/pwpd_cert.conf')
DEFAULT_TIMEOUT = 15
DEFAULT_URL = ''


def push_req_task(ppdetector, dname, pwsd_ll):
    ppdetector.push_task('http://' + dname)
    #
    for ll in pwsd_ll:
        url = 'http://' + dname + '/' + ll
        ppdetector.push_task(url)

def construct_path(pwsd_level):
    pwsd_ll = list()
    #
    for pprl in pwsd_level[0][1]:
        #
        pwsd_ll.append(pprl.dirt)
        #
        if not pprl.is_end:
            ll = construct_path(pwsd_level[1:])
            for lll in ll:
                pwsd_ll.append(pprl.dirt + '/' + lll)
        
    return pwsd_ll

def get_relpath(path):
    return os.path.join(os.getcwd(), path)

def do_main(args):
    #
    config_file = DEFAULT_CONFIG
    # load config and initialize logger
    cfg = config.load_config(config_file)
    logfile = os.path.join(os.getcwd(), cfg.get_opt(config.OPT_LOGDIR), 'pwpd.log')
    logger = pwdlogging.get_logger("pwd.daemon.cmdmain", logfile , default = True)
    
    if len(args) != 2:
        timeout = DEFAULT_TIMEOUT
        out_url = DEFAULT_URL
    else:
        timeout = int(args[0])
        out_url = args[1]

    TT_Start = time.time()
    
    runner = pwdcore.PWPDRunner(cfg, timeout, out_url)
    runner.detecting_start()

    TT_elapse = time.time() - TT_Start 
    
    logger.info("############### time elapse: %f | Thread num: %s ###############", TT_elapse, cfg.get_opt(config.OPT_WORK_NUM))
    print '=====>>>>> completed! Clock elapse: %f' % TT_elapse
    # =========================================

if __name__ == '__main__':

    args = sys.argv[1:]
    do_main(args)

    
    
